package testProject;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.onpositive.page.pagerendering.AccountsManagementRenderer;
import com.onpositive.storage.managers.AccountManager;

public class AuthorizationFilter implements javax.servlet.Filter {

	public void destroy() {
		// 

	}

	private static ServletContext context;

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest rq = (HttpServletRequest) arg0;
		HttpServletResponse rs = (HttpServletResponse) arg1;

		String reqURI = rq.getRequestURI();
		String parentUrl = reqURI.replaceAll("\\"
				+ AccountsManagementRenderer.LOGIN_SUFFIX, "");
		reqURI = "/index";
		rq.getSession(true).setAttribute("host", parentUrl);// .replaceAll("/",""));
		// rq.setAttribute("host",parentUrl);

		if (AccountManager.isUserLoginned()) {
			String createLogoutURL = AccountManager.getService()
					.createLogoutURL(parentUrl);
			//RequestDispatcher rd = context
			//		.getRequestDispatcher(createLogoutURL);
			//rd.forward(rq, rs);

			 rs.sendRedirect(createLogoutURL);
		} else {
			String createLoginURL = AccountManager.getService().createLoginURL(
					reqURI);
			//RequestDispatcher rd = context.getRequestDispatcher(createLoginURL);
			//rd.forward(rq, rs);
			 rs.sendRedirect(createLoginURL);
		}

	}

	public void init(FilterConfig arg0) throws ServletException {
		context = arg0.getServletContext();
	}

}
